from django.db import models
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from user.models import User
from playai.settings import ROBOT_ROOT
import os


class Game(models.Model):
	name = models.CharField(max_length=50)
	url = models.CharField(max_length=20, unique=True)
	code_size = models.IntegerField(default=1048576)
	into = models.TextField()
	io = models.TextField()
	example = models.TextField(null=True, blank=True)

	def __str__(self):
		return "<Game: {0}>".format(self.name)


class Robot(models.Model):
	name = models.CharField(max_length=50)
	user = models.ForeignKey(User)
	game = models.ForeignKey(Game)
	code = models.FileField(upload_to=ROBOT_ROOT)

	def __str__(self):
		return "<Robot: {0} - {1} - {2}>".format(self.game.name, self.user.username, self.name)

@receiver(pre_delete, sender=Robot)
def onRobotDelete(sender, instance, **kwargs):
	if os.path.exists(instance.code.name):
		os.remove(instance.code.name)